layui.define(['jquery', 'ztree', 'common', 'toast', 'dropdown', 'layer'], function (exports) {
    "use strict";

    /**
     * 常用封装类
     * */
    var MOD_NAME = 'busGroup',
        $ = layui.jquery,
        ztree = layui.ztree,
        common = layui.common,
        layer = layui.layer,
        dropdown = layui.dropdown,
        toast = layui.toast;

    let options = {
        treeId: "ztree",
        contextmenu: "contextmenu",
        zNodes: []
    };

    var busGroup = new function () {

        this.setData = (data) => {
            options.zNodes = data;
            this.treeObj.destroy();
            this.treeObj = $.fn.zTree.init($("#" + options.treeId + ""), this.setting, data);
            this.treeObj.expandAll(true);
        }
        /**
         * 初始化业务分组树
         * @param opt
         */
        this.init = (opt) => {
            let treeObj;
            let setting;
            options = $.extend({}, options, opt);
            setting = {
                view: {

                },
                data: {
                    simpleData: {
                        enable: true,
                        idKey: "id",
                        pIdKey: "pid",
                        rootPId: ""
                    },
                    key: {
                        name: "group_name"
                    },

                }
                , check: {
                    enable: true,
                    chkStyle: "checkbox",
                    chkboxType: {"Y": "s", "N": "s"}
                }
                , edit: {
                    enable: true,
                    drag: {
                        isCopy: false,
                        isMove: true
                    },
                    showRemoveBtn: false,
                    showRenameBtn: false
                }
                , callback: {
                    onDblClick: function (event, treeId, treeNode) {
                        vue_business_model.$data.selectGroup = treeNode.getPath();
                        vue_business_model.$data.selectGroupId = treeNode.id;
                        vue_business_model.$data.queryBusModel.groups = treeNode.getPath().map(item=>item.id).join(",")
                        vue_business_model.$data.queryBusModel.page = 1
                        vue_business_model.getBusList();
                    }
                    ,onDrop: async function (
                        event, treeId, treeNodes, targetNode, moveType
                    ) {
                        var zTree = $.fn.zTree.getZTreeObj(treeId);
                        var paramData = [];
                        var nodeData = [];
                        //子节点拖拽到跟节点 和 根节点的相互排序
                        if (targetNode == null || treeNodes[0].level == 0) {
                            nodeData = zTree.getNodesByParam("level", 0);
                        } else {
                            // 拖拽自己成为子节点
                            var node = zTree.getNodeByTId(treeNodes[0].parentTId);
                            if (node.isParent) {
                                nodeData = zTree.transformToArray(node.children);
                            }
                        }
                        $.each(nodeData, function (i, item) {
                            var item_data = {};
                            item_data["id"] = item.id;
                            item_data["pid"] = item.pid;
                            item_data["order_index"] = item.getIndex();//核心：当前节点同级的下标位
                            paramData.push(item_data);
                        });
                        //得到这次操作需要变更的数据范围
                        console.log(paramData);
                        let res_data = await common.ajax({
                            url:apiUrlConfig.businessGroup.saveOrderIndex,
                            data:JSON.stringify(paramData)
                        })
                        toast.success({title: false, message: '保存成功'})
                    },
                }
            };
            let zNodes = options.zNodes;
            treeObj = $.fn.zTree.init($("#" + options.treeId + ""), setting, zNodes);
            treeObj.expandAll(true);

            //绑定邮件菜单
            // 右键菜单
            dropdown.render({
                elem: '#' + options.contextmenu, // 也可绑定到 document，从而重置整个右键
                trigger: 'contextmenu', // contextmenu
                isAllowSpread: false, // 禁止菜单组展开收缩
                style: 'width: 200px', // 定义宽度，默认自适应
                data: [{
                    title: '新增',
                    id: 'add',
                }, {
                    title: '修改',
                    id: 'update',
                }, {
                    title: '删除',
                    id: 'del'
                }, {
                    title: '刷新',
                    id: 'reload'
                }, {
                    title: '展开',
                    id: 'expand'
                }, {
                    title: '折叠',
                    id: 'fold'
                }],
                click: function (obj, othis) {
                    if (obj.id === 'add') {
                        //获取当前选中的 节点
                        let nodes = treeObj.getSelectedNodes();
                        let select_node = null;
                        if (nodes.length > 0) {
                            select_node = nodes[0];
                        }
                        let title = "在根目录添加业务分组";
                        if (select_node != null) {
                            title = `在【${select_node.group_name}】下新增业务分组`;
                        }
                        let pid = "";
                        if (select_node != null) {
                            pid = select_node.id
                        }
                        layer.open({
                            type: 2,
                            title: title,
                            area: ['90%', '90%'],
                            content: 'business_add.html?id=' + pid
                        });
                    } else if (obj.id === 'del') {
                        var nodes = treeObj.getCheckedNodes(true);
                        if (nodes.length == 0) {
                            toast.error({title: false, message: '请勾选要删除的业务分组'})
                            return
                        }
                        let ids = nodes.map(item=>item.id)
                        layer.confirm('确定要删除么', {icon: 3, title: '提示'}, async function (index) {
                            layer.close(index);
                            let res_data = await common.ajax({
                                url: apiUrlConfig.businessGroup.delete,
                                data: JSON.stringify(ids),
                            })
                            toast.success({title: false, message: '删除成功'})
                            for (var i=0, l=nodes.length; i < l; i++) {
                                treeObj.removeNode(nodes[i]);
                            }
                        });
                    } else if (obj.id === 'update') {
                        //获取当前选中的 节点
                        let nodes = treeObj.getSelectedNodes();
                        let select_node = null;
                        if (nodes.length > 0) {
                            select_node = nodes[0];
                        }
                        if(select_node== null){
                            toast.error({title: false, message: '请选择要编辑的业务分组'});
                        }

                        let id = "";
                        if (select_node != null) {
                            id = select_node.id
                        }
                        layer.open({
                            type: 2,
                            title: "修改【"+select_node.group_name+"】",
                            area: ['90%', '90%'],
                            content: 'business_edit.html?id=' + id
                        });
                    } else if (obj.id === 'reload') {
                    } else if (obj.id === 'expand') {
                        treeObj.expandAll(true);
                    } else if (obj.id === 'fold') {
                        treeObj.expandAll(false);
                    }
                },
                ready: function (elemPanel, elem) {
                    var tagName = elem.context.activeElement.tagName;
                    if (tagName == 'LI') {
                        let nodeid = elem.context.activeElement.id.replace(options.treeId + "_", "");
                        var node = treeObj.getNodeByTId(nodeid);
                        treeObj.selectNode(node);
                    } else {
                        //取消所有选中
                        treeObj.cancelSelectedNode();
                    }
                    this.activeElement = elem.context.activeElement;
                }
            });
            this.treeObj = treeObj;
            this.setting = setting;
            this.options = options;
            return this;
        }


    }
    exports(MOD_NAME, busGroup);
});
